package com.farm.kaiping.entity;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
public class FarmUser implements UserDetails {

    private Integer userId;
    private String username;
    private String realName;
    private String phone;
    private String avatar;
    private String idCard;
    private Integer sex;
    private LocalDate birthDay;

    private Integer deptId;
    private String deptName;
    private Integer roleId;
    private String roleName;
    private String roleCode;
    private Integer classifyId;
    private Integer tenantId;

    private String wxOpenid;
    private String wxUnionid;
    private String miniOpenid;

    private LocalDateTime passwordModifyTime;
    private LocalDateTime loginTime;
    private LocalDateTime createTime;
    private LocalDateTime updateTime;
    private String token;
    private Integer tokenExpireTime;

    private List<String> permissions;

    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities;

    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (ObjectUtil.isNotEmpty(authorities)) {
            return authorities;
        }
        if (ObjectUtil.isNotEmpty(permissions)) {
            return permissions.stream().filter(ObjectUtil::isNotEmpty).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        }
        return authorities;
    }

    @Override
    @JsonIgnore
    public String getPassword() {
        return null;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    /**
     * 判断用户是否过期
     */
    @Override
    @JsonIgnore
    public boolean isAccountNonExpired() {
        return true;
    }

    /*
     * 判断用户是否被锁定
     * 一般用于多次登录失败。
     */
    @Override
    @JsonIgnore
    public boolean isAccountNonLocked() {
        return true;
    }

    /*
     * 用于判断用户的凭证（密码）是否过期
     */
    @Override
    @JsonIgnore
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /*
     * 判断用户是否被禁用
     */
    @Override
    @JsonIgnore
    public boolean isEnabled() {
        return true;
    }

    @Override
    public String toString() {
        return "FarmUser{" +
                "id=" + (userId != null ? userId : "null") +
                ", username=" + (username != null ? username : "null") +
                ", realName=" + (realName != null ? realName : "null") +
                "}";
    }

}
